package thread.word_matching;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/*
    线程调度类
 */
public class WordMatchingClassifier {
    public static Distance classify(String word, List<String> list) throws InterruptedException, ExecutionException {
        Distance result = new Distance();
        //任务数
        int numThread = Runtime.getRuntime().availableProcessors();
        //创建线程池
        ThreadPoolExecutor executor =
                (ThreadPoolExecutor) Executors.newFixedThreadPool(numThread);
        //计算每个线程的计算量
        //每个任务的大小
        int step = list.size() / numThread;
        //每个任务的起始位置
        int start = 0;
        //每个任务的结束位置
        int end = step;
        List<WordMatchingTask> tasks = new ArrayList<>();
        for (int i=0;i<numThread;i++){
            start = i * step;
            if (i == numThread - 1)
                end = list.size();
            else
                end = start + step;
            WordMatchingTask task = new WordMatchingTask(word, list, start, end);
            tasks.add(task);
        }
        //invokeAll一次性提交所有的任务，只有所有任务都执行完，才会继续执行主线程
        //即线程会阻塞在这里
        List<Future<Distance>> futures = executor.invokeAll(tasks);//一次性提交所有任务
        //关闭线程池
        executor.shutdown();

        int minDistance = Integer.MAX_VALUE;
        List<String> minList = new ArrayList<>();
        //循环获取结果
        for (Future<Distance> future:futures) {
            Distance temp = future.get();
            if (temp.getDistance() < minDistance){
                minDistance = temp.getDistance();
                minList.clear();
            }
            if (temp.getDistance() == minDistance){
                minList.addAll(temp.getWordList());
            }
        }
        result.setDistance(minDistance);
        result.setWordList(minList);
        System.out.println("classifier result= "+result);
        return result;
    }
}
